package cn.wolfcode.shop.seckill.web.frontend;

import cn.wolfcode.cloud.redis.RedisService;
import cn.wolfcode.cloud.result.Result;
import cn.wolfcode.shop.member.domain.User;
import cn.wolfcode.shop.seckill.redis.SeckillKeyPrefix;
import cn.wolfcode.shop.seckill.service.ISeckillGoodService;
import cn.wolfcode.shop.seckill.vo.SeckillGoodVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/seckillGood")
public class SeckillController {

    @Autowired
    private ISeckillGoodService seckillGoodService;

    @Autowired
    private RedisService redisService;

    @RequestMapping("/query")
    public Result<List<SeckillGoodVo>> query(){
        List<SeckillGoodVo> query = seckillGoodService.queryByCache();
        for (SeckillGoodVo seckillGoodVo:query) {
            Integer stock = redisService.get(SeckillKeyPrefix.SECKILLGOODSTOCK, seckillGoodVo.getId() + "", Integer.class);
            if(stock < 0){
                stock=0;
            }
            seckillGoodVo.setStockCount(stock);
        }
        return Result.success(query);
    }

    @RequestMapping("/findById")
    public Result<SeckillGoodVo> findById(@RequestParam("id") Long id){
        SeckillGoodVo seckillGoodVo = seckillGoodService.findCacheById(id);
        Integer stock = redisService.get(SeckillKeyPrefix.SECKILLGOODSTOCK, id + "", Integer.class);
        if(stock < 0){
            stock=0;
        }
        seckillGoodVo.setStockCount(stock);
        return Result.success(seckillGoodVo);
    }
    @RequestMapping("initGoods")
    public Result<Boolean> initGoods(){
        seckillGoodService.initGoodsToCache();
        return Result.success(true);
    }
}
